<template>
  <div class="user-container">
    <el-card class="operation-card">
      <div class="operation-area">
        <!-- 左侧按钮区域 -->
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增用户
          </el-button>
          <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon> 导出用户
          </el-button>
        </div>

        <!-- 右侧搜索区域 -->
        <div class="search-container">
          <el-input
            v-model="searchParams.keyword"
            placeholder="请输入用户名/邮箱/手机号/昵称"
            clearable
            style="width: 300px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>

          <el-select v-model="searchParams.status" placeholder="用户状态" clearable @change="handleSearch" style="width: 130px; margin-left: 10px;">
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>

          <el-button @click="resetSearch" style="margin-left: 10px;">
            <el-icon><RefreshRight /></el-icon> 重置
          </el-button>
        </div>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="id" label="ID" show-overflow-tooltip /> -->
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="department" label="部门" />
        <!-- <el-table-column prop="position" label="职位" /> -->
        <el-table-column prop="phone" label="手机号码" />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_login_time" label="最后登录时间" />
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <div class="action-container">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  class="action-button"
                  type="primary"
                  circle
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="重置密码" placement="top">
                <el-button
                  class="action-button"
                  type="success"
                  circle
                  size="small"
                  @click="handleResetPwd(scope.row)"
                >
                  <el-icon><Key /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="分配角色" placement="top">
                <el-button
                  class="action-button"
                  type="warning"
                  circle
                  size="small"
                  @click="handleAssignRole(scope.row)"
                >
                  <el-icon><UserFilled /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip v-if="scope.row.username !== 'admin'" content="删除" placement="top">
                <el-button
                  class="action-button"
                  type="danger"
                  circle
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="userForm.isAdd ? '新增用户' : '编辑用户'"
      v-model="dialogVisible"
      width="600px"
         :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
      destroy-on-close
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        style="max-width: 560px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="!userForm.isAdd"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item v-if="userForm.isAdd" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" style="display: none;">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="userForm.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="userForm.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio-button :label="1">男</el-radio-button>
            <el-radio-button :label="2">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio-button :label="1">正常</el-radio-button>
            <el-radio-button :label="0">停用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置密码"
      v-model="resetPwdDialogVisible"
      width="500px"
         :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
      destroy-on-close
    >
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPwdForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPwdForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPwdDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResetPwd">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      title="分配角色"
      v-model="roleDialogVisible"
      width="700px"
         :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
      destroy-on-close
    >
      <div v-if="loading" class="role-loading">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-else>
        <el-transfer
          v-model="userRoleIds"
          :data="allRoles"
          :props="{
            key: 'id',
            label: 'name'
          }"
          :titles="['未分配', '已分配']"
          filterable
          filter-placeholder="请输入角色名称"
        />
        <div class="role-description" v-if="selectedRoleDescription">
          <div class="role-description-title">角色说明：</div>
          <div>{{ selectedRoleDescription }}</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleAssign" :loading="submitting">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  Plus,
  Edit,
  Delete,
  Download,
  Key,
  Search,
  RefreshRight,
  UserFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElTag, ElButton } from 'element-plus'
import { getUserList, createUser, updateUser, deleteUser, resetUserPassword } from '@/api/user'
import { getRoleList, assignRoleToUser } from '@/api/role'

// 定义组件名
defineOptions({
  name: 'UserListPage'
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const resetPwdDialogVisible = ref(false)
const userFormRef = ref(null)
const resetPwdFormRef = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: ''
})

// 选择行变化处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 用户表单数据
const userForm = reactive({
  id: '',
  username: '',
  nickname: '',
  phone: '',
  email: '',
  department: '',
  position: '',
  gender: 0,
  status: 1,
  password: '',
  isAdd: true
})

// 重置密码表单数据
const resetPwdForm = reactive({
  userId: '',
  password: '',
  confirmPassword: ''
})

// 表单校验规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 重置密码表单校验规则
const resetPwdRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 角色分配相关
const roleDialogVisible = ref(false)
const allRoles = ref([])
const userRoleIds = ref([])
const currentUserId = ref('')
const selectedRoleDescription = ref('')
const submitting = ref(false)

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  // 构建请求参数，包含分页和搜索参数
  const params = {
    skip: (pagination.currentPage - 1) * pagination.pageSize,
    limit: pagination.pageSize
  }

  // 添加搜索条件
  if (searchParams.keyword) {
    params.keyword = searchParams.keyword
  }

  if (searchParams.status !== '') {
    params.status = searchParams.status
  }

  try {
    const res = await getUserList(params)

    // 检查返回的数据结构，确保items存在
    if (res && res.items && Array.isArray(res.items)) {
      tableData.value = JSON.parse(JSON.stringify(res.items));
      pagination.total = res.total || 0
    } else {
      console.error('未能识别API返回的数据结构:', res)
      // 清空数据
      tableData.value = []
      pagination.total = 0
      ElMessage.error('获取用户列表失败，API返回格式不正确')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败: ' + (error.message || '未知错误'))
    console.error('获取用户列表失败:', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 将表格数据映射到API提交格式
const mapTableUserToApi = (form) => {
  return {
    id: form.id,
    username: form.username,
    nickname: form.nickname,
    phone: form.phone,
    email: form.email,
    gender: form.gender,
    department: form.department,
    position: form.position,
    status: form.status,
  }
}

// 初始化数据
onMounted(() => {
  fetchUserList()
})

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchUserList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchUserList()
}

// 新增用户
const handleAdd = () => {
  Object.keys(userForm).forEach(key => {
    if (key === 'status') userForm[key] = 1
    else if (key === 'gender') userForm[key] = 1  // 默认设置为男性
    else if (key === 'isAdd') userForm[key] = true
    else userForm[key] = ''
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  Object.keys(userForm).forEach(key => {
    if (key in row) {
      userForm[key] = row[key]
    }
  })
  userForm.isAdd = false
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员账号不能删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除用户【${row.username}】吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用删除API
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      console.error('删除用户失败:', error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  if (selectedRows.value.some(row => row.username === 'admin')) {
    ElMessage.warning('选中的用户包含超级管理员，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}条记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 批量删除用户
      const deletePromises = selectedRows.value.map(row => deleteUser(row.id))
      await Promise.all(deletePromises)

      ElMessage.success('批量删除成功')
      // 重置选择
      selectedRows.value = []
      // 刷新数据
      fetchUserList()
    } catch (error) {
      ElMessage.error('批量删除失败: ' + (error.message || '未知错误'))
      console.error('批量删除用户失败:', error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 重置密码
const handleResetPwd = (row) => {
  resetPwdForm.userId = row.id
  resetPwdForm.password = ''
  resetPwdForm.confirmPassword = ''
  resetPwdDialogVisible.value = true
}

// 提交重置密码
const submitResetPwd = async () => {
  try {
    await resetPwdFormRef.value.validate()

    // 调用重置密码API
    await resetUserPassword(resetPwdForm.userId, {
      password: resetPwdForm.password,
      confirmPassword: resetPwdForm.confirmPassword
    })

    ElMessage.success('密码重置成功')
    resetPwdDialogVisible.value = false
  } catch (error) {
    ElMessage.error('密码重置失败: ' + (error.message || '未知错误'))
    console.error('密码重置失败:', error)
  }
}

// 导出用户
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.status = ''
  pagination.currentPage = 1
  fetchUserList()
}

// 提交表单
const submitForm = async () => {
  try {
    await userFormRef.value.validate()

    // 准备API提交数据
    const apiData = mapTableUserToApi(userForm)

    if (userForm.isAdd) {
      // 添加注册接口所需的密码字段
      apiData.password = userForm.password
      apiData.email = userForm.username + '@datatk.com'
      await createUser(apiData)
      ElMessage.success('添加成功')
    } else {
      // 调用更新用户API
      await updateUser(userForm.id, apiData)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    ElMessage.error((userForm.isAdd ? '添加失败' : '更新失败') + ': ' + (error.message || '未知错误'))
    console.error('表单提交失败:', error)
  }
}

// 获取所有角色
const fetchAllRoles = async () => {
  try {
    const res = await getRoleList({ limit: 100 })
    if (res && res.items && Array.isArray(res.items)) {
      allRoles.value = res.items.map(item => ({
        id: item.id,
        name: item.name,
        description: item.description || ''
      }))
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败: ' + (error.message || '未知错误'))
  }
}

// 监听角色选择变化
watch(userRoleIds, (newVal) => {
  if (newVal.length === 1) {
    const selectedRole = allRoles.value.find(role => role.id === newVal[0])
    selectedRoleDescription.value = selectedRole ? selectedRole.description : ''
  } else {
    selectedRoleDescription.value = ''
  }
})

// 处理分配角色
const handleAssignRole = (row) => {
  currentUserId.value = row.id
  fetchAllRoles()
  // 这里应该调用接口获取用户当前的角色列表
  // 由于接口文档中没有专门查询用户角色的API，这里模拟一下
  // 实际项目中需要替换为真实API调用
  userRoleIds.value = row.roles?.map(role => role.id) || []
  roleDialogVisible.value = true
}

// 提交角色分配
const submitRoleAssign = async () => {
  if (!currentUserId.value) return

  submitting.value = true
  try {
    // 这里简化处理，实际上应该比较原有角色和新选择的角色
    // 分别执行添加和删除操作
    for (const roleId of userRoleIds.value) {
      await assignRoleToUser(currentUserId.value, { role_id: roleId })
    }

    ElMessage.success('角色分配成功')
    roleDialogVisible.value = false
    fetchUserList() // 刷新用户列表
  } catch (error) {
    ElMessage.error('角色分配失败: ' + (error.message || '未知错误'))
    console.error('角色分配失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.user-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
  box-sizing: border-box;
}

.operation-card {
  margin-bottom: 20px;
  width: 100%;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.table-card {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.action-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-button {
  font-size: 12px;
  border: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.search-container {
  display: flex;
  align-items: center;
}

.role-loading {
  padding: 20px 0;
}

.role-description {
  margin-top: 15px;
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.role-description-title {
  font-weight: bold;
  margin-bottom: 5px;
}
</style>
